package o2o.web.actions.order;

import com.jinyou.utils.common.*;
import o2o.cache.agent.CityAgentMemory;
import o2o.cache.agent.ShopAgentRelationMemory;
import o2o.cache.postman.CityPostmanMemory;
import o2o.cache.postman.PostManLikeMemory;
import o2o.cache.shop.ShopMemory;
import o2o.cache.sys.SysVariablePaotuiMemory;
import o2o.cache.user.UserAddressMemory;
import o2o.dao.PO.agent.CityAgent;
import o2o.dao.PO.order.*;
import o2o.postman.model.CityPostman;
import o2o.dao.PO.postman.PostManLike;
import o2o.company.model.ShopInfo;
import o2o.dao.PO.sys.SysVariablePaotui;
import o2o.dao.PO.user.UserAddress;
import o2o.system.data.POSTMAN_IN_CITY_OR_AGENT_DATA;
import o2o.system.data.SHOP_MANAGE_TYPE_FREE_OR_AGENT;
import o2o.system.data.SYS_SETTINGS;
import org.apache.commons.lang.StringUtils;

import java.util.List;

//提交订单管理类
public class SubmitOrderCal {


    public static OrderSubmitCalResult calculateOrderMoney(String sysAppKey,
                                                           String submitUsername, Long shopId,
                                                           Long deliveryId,
                                                           Integer isUrgent,
                                                           String goodsInfoJson,
                                                           Integer isZiQu,
                                                           Double buyLat, Double buyLng,
                                                           Double taxMoney
    ) {

        OrderSubmitCalResult orderSubmitResult = new OrderSubmitCalResult();
        if (ValidateUtil.isNull(goodsInfoJson)) {
            orderSubmitResult.setSuccess(false);
            orderSubmitResult.setError("请先选购商品");
            return orderSubmitResult;
        }

        //店铺信息
        ShopInfo shopInfo = null;
        if (null != shopId && shopId > 0) {
            shopInfo = ShopMemory.getInstance().getShopById(shopId);
            if (null == shopInfo) {
                orderSubmitResult.setSuccess(false);
                orderSubmitResult.setError("当前店铺已不存在，请核对后重试");
                return orderSubmitResult;
            }
        }
        Double deliveryPrice = 0d;
        Double shopPacketMoney = 0d;


        // 积分兑换商品不在验证用户的地理位置和活动等信息
        Long agentId = null;
        UserAddress userAddress = UserAddressMemory.getInstance().getAddressInfo(deliveryId);

        //订单对应的代理信息
        agentId = ShopAgentRelationMemory.getInstance().getAgentByShopId(shopId);
        CityAgent cityAgent;
        if (ValidateUtil.isNotID(agentId)) {
            cityAgent = CityAgentMemory.getInstance().getByUsername(shopInfo.getOwnUsername());
            if (null == cityAgent) {
                //如果配送员配送是按商圈划分的 那么提交订单必须要商圈信息
                if (ValidateUtil.isAbsInteger(SYS_SETTINGS.POSTMAN_IN_CITY_OR_AGENT) && (0 == POSTMAN_IN_CITY_OR_AGENT_DATA.AGENT - SYS_SETTINGS.POSTMAN_IN_CITY_OR_AGENT || 0 == POSTMAN_IN_CITY_OR_AGENT_DATA.FREE_AGENT - SYS_SETTINGS.POSTMAN_IN_CITY_OR_AGENT)) {
                    if (null != isZiQu && 0 == isZiQu) {
                        orderSubmitResult.setSuccess(false);
                        orderSubmitResult.setError("当前店铺信息有误，请联系客服[该店铺没有管理代理信息]");
                        return orderSubmitResult;
                    }
                }
            } else {
                agentId = cityAgent.getId();
            }
        } else {
            cityAgent = CityAgentMemory.getInstance().getById(agentId);
        }


        //配送费处理
        if (null != isZiQu && 0 == isZiQu) { //需要配送
            if (ValidateUtil.isID(deliveryId)) {//配送
                if (null == userAddress) {
                    orderSubmitResult.setSuccess(false);
                    orderSubmitResult.setError("请核对送货地址后重试");
                    return orderSubmitResult;
                }
            }

            // 是否启用电子围栏 0.不使用电子围栏 1.使用电子围栏(商圈) 2.使用电子围栏(店铺)
            if (null != SYS_SETTINGS.IS_ELECTRONIC_FENCE && (0 == 1 - SYS_SETTINGS.IS_ELECTRONIC_FENCE || 0 == 2 - SYS_SETTINGS.IS_ELECTRONIC_FENCE)) {
                orderSubmitResult = doDeliveryPriceV2(isZiQu, shopInfo,
                        userAddress, agentId,
                        cityAgent, deliveryPrice,
                        buyLat, buyLng,
                        orderSubmitResult);
            } else {
                orderSubmitResult = doDeliveryPrice(isZiQu, shopInfo,
                        userAddress, agentId,
                        cityAgent, deliveryPrice,
                        buyLat, buyLng,
                        orderSubmitResult);
            }


            if (null != orderSubmitResult) {
                if (orderSubmitResult.isSuccess()) {
                    deliveryPrice = orderSubmitResult.getOrderDeliveryPrice();
                } else {
                    return orderSubmitResult;
                }
            } else {
                orderSubmitResult.setSuccess(false);
                orderSubmitResult.setError("验证配送费错误，请稍后再试");
                return orderSubmitResult;
            }
        }

        //打包费
        if (null != shopInfo && null != shopInfo.getPacketPrice()) {
            shopPacketMoney = shopInfo.getPacketPrice();
        } else {
            shopPacketMoney = 0d;
        }

        //加急配送费
        Double urgentPrice = 0d;
        if (null != SYS_SETTINGS.URGENT_DELIVERY_PRICE) {
            urgentPrice = Double.parseDouble(SYS_SETTINGS.URGENT_DELIVERY_PRICE + "");
        }
        if (ValidateUtil.isNotAbsInteger(isUrgent)) {
            isUrgent = 0;
        }

        //验证配送费
        if (ValidateUtil.isAbsInteger(isZiQu) && 0 == isZiQu) { //配送的才去验证   0配送  1自取
            //配送费计算方式
            if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 2 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) {//配送费计算方式 1固定配送费 2按距离计算 3. 按距离（店铺）
                //按距离(平台)计算，验证收货地址时已经验证过了
            } else if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 3 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) {//配送费计算方式 1固定配送费 2按距离计算 3. 按距离（店铺）
                //按距离（店铺）计算，验证收货地址时已经验证过了
            } else {
                deliveryPrice = shopInfo.getYunfei();
            }

            //添加加急费
            if (0 == 1 - isUrgent) {//如果是加急
                deliveryPrice = JYMathDoubleUtils.add(urgentPrice, deliveryPrice);
            }
        }


        //商品信息
        int totalCount = 0;
        double totalMoney = 0;//订单总金额
        double totalWeight = 0;//商品总重量
        double totalGoodsMoney = 0;//商品总金额（不含打包费）
        double totalPacketMoney = 0;// 单独每个商品打包费合计金额
        double totalGoodsAndPacketMoney = 0;// 单独每个商品及打包费 合计金额
        double taxMoneyV1 = 0;
        boolean hasUsedZhekou = false;//是否已经使用过折扣（商品现价比原价少）

        // 陈鲜生  商品重量参与配送费计算
        if (SYS_SETTINGS.IS_WEIGHT_ADD_DELIVERY != null && SYS_SETTINGS.IS_WEIGHT_ADD_DELIVERY == 1) {
            // 重量参与配送费计算
            orderSubmitResult = doOrderWeightDeliveryPrice(isZiQu, totalWeight, deliveryPrice, shopInfo, agentId, orderSubmitResult);
            if (null != orderSubmitResult) {
                if (orderSubmitResult.isSuccess()) {
                    deliveryPrice = orderSubmitResult.getOrderDeliveryPrice();
                } else {
                    return orderSubmitResult;
                }
            }
        }

        if (ValidateUtil.isAbsInteger(isZiQu) && 0 == 2 - isZiQu) { //  堂食
            deliveryPrice = 0d;
            shopPacketMoney = 0d;
        }

        //3. 订单信息保存
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setTotalWeight(totalWeight);
        orderInfo.setAgentId(agentId);
        orderInfo.setIsUrgent(isUrgent);//是否加急

        //店铺配送方式
        if (null != shopInfo && null != shopInfo.getIsSelfPost()) {
            orderInfo.setShopSelfPost(shopInfo.getIsSelfPost());
        }

        //订单金额
        orderInfo.setTotalCount(totalCount); //购买数量(几件商品)
        orderInfo.setTotalGoodsMoney(totalGoodsMoney); //商品总金额
        totalGoodsAndPacketMoney = JYMathDoubleUtils.add(totalGoodsMoney, totalPacketMoney);// 订单总金额加上每个商品打包费c
        totalMoney = JYMathDoubleUtils.add(totalGoodsAndPacketMoney, shopPacketMoney);// 订单总金额加上店铺打包费

        //商品金额满足一定金额时 免配送费  add by zhuwx
        //V2 满足金额减配送费（非免配送费）
        if (null != shopInfo && ValidateUtil.isAbsDouble(shopInfo.getFreeYunFei())) {
            if (JYMathDoubleUtils.sub(shopInfo.getFreeYunFei(), totalGoodsAndPacketMoney) <= 0) {
                //记录原始配送费及店铺减免配送费部分金额
                orderInfo.setOriginalYunFei(deliveryPrice);
                orderInfo.setOriginalYunFeiShop(shopInfo.getFreeYunFeiShop());
                if (null != shopInfo.getFreeYunFeiShop() && null != shopInfo.getFreeYunFeiMoney()
                        && 0 == -1 - shopInfo.getFreeYunFeiMoney() && -1 - shopInfo.getFreeYunFeiShop() == 0) {
                    orderInfo.setOriginalYunFeiShop(deliveryPrice);
                }
                //设置本订单实际收取的配送费
                if (null != shopInfo.getFreeYunFeiMoney()) {
                    if (0 == -1 - shopInfo.getFreeYunFeiMoney()) {
                        //免配送费
                        deliveryPrice = 0d;
                    } else {
                        //减配送费
                        deliveryPrice = JYMathDoubleUtils.sub(deliveryPrice, shopInfo.getFreeYunFeiMoney());
                        // yangtk 2019年4月17日14:52:35
                        if (deliveryPrice < 0) {
                            deliveryPrice = 0d;
                        }
                        // end
                    }
                }
            }
        }

        totalMoney = JYMathDoubleUtils.add(totalMoney, deliveryPrice);//订单总金额加上配送费
        orderInfo.setTotalPrice(totalMoney);//订单总金额
        orderInfo.setDeliveryPrice(deliveryPrice);//配送费
        orderInfo.setPacketPrice(JYMathDoubleUtils.add(shopPacketMoney, totalPacketMoney));//店铺打包费+每个商品的


        orderInfo.setShopLat(shopInfo.getLat());//店铺纬度
        orderInfo.setShopLng(shopInfo.getLng());//店铺经度


        Double mustPayMoney = totalMoney;//必须支付金额
        Double awardMoney = 0d;//奖励金额
        Double platformAwardMoney = 0d;//平台奖励金额
        Double shopAwardMoney = 0d;//店铺奖励金额
        orderInfo.setAwardMoney(awardMoney);
        orderInfo.setPlatformAwardMoney(platformAwardMoney);
        orderInfo.setShopAwardMoney(shopAwardMoney);
        orderInfo.setTotalPrice(mustPayMoney);//待支付金额
        orderInfo.setTotalMoney(totalMoney);//订单总金额
        orderInfo.setShopId(shopId);//订单总金额


        orderSubmitResult.setSuccess(true);
        orderSubmitResult.setOrderTotalMoney(totalMoney);
        orderSubmitResult.setMustPayMoney(mustPayMoney);
        orderSubmitResult.setAwardMoney(awardMoney);
        return orderSubmitResult;
    }


    // 是否指定为收藏的配送员 true 标识 收藏者优先  false 一样
    public static boolean isSpecifiedPostmen(String username, String city, Integer postmanType) {
        if (SYS_SETTINGS.POSTMAN_LIKE_IS_FIRST == null
                || SYS_SETTINGS.POSTMAN_LIKE_IS_FIRST == 0
                || SYS_SETTINGS.LIKE_POSTMAN_UNROB_TIME == null
                || SYS_SETTINGS.LIKE_POSTMAN_UNROB_TIME <= 0
                || ValidateUtil.isNull(username)
                || ValidateUtil.isNull(city)) {
            return false;
        }
        List<PostManLike> list = PostManLikeMemory.getInstance().listOfPostManLikeByUsername(username);
        if (ValidateUtil.isAbsList(list)) {
            for (PostManLike p : list) {
                if (p == null) {
                    continue;
                }
                CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(p.getPostman());
                if (cityPostman == null) {
                    continue;
                }
                if (city.equals(cityPostman.getCity()) && cityPostman.getIsWork() == 1) {
                    // 有一个就行
                    if (postmanType != null) {
                        if (cityPostman.getType() != null && cityPostman.getType() == postmanType) {
                            return true;
                        } else {
                            return false;
                        }
                    } else {
                        return true;
                    }
                }
            }
        }
        return false;
    }


    //保存活动信息
    private static OrderSubmitResult saveGameInfo(Long gameId, Long gameRuleId,
                                                  OrderInfo orderInfo, Long time,
                                                  Double totalPrice,
                                                  Double awardMoney, Double platformAwardMoney, Double shopAwardMoney,
                                                  Double mustPayMoney,
                                                  String submitUsername) {
        OrderSubmitResult orderSubmitResult = new OrderSubmitResult();


        orderSubmitResult.setSuccess(true);
        orderSubmitResult.setOrderTotalMoney(totalPrice);
        orderSubmitResult.setMustPayMoney(mustPayMoney);
        orderSubmitResult.setAwardMoney(awardMoney);
        orderSubmitResult.setPlatformAwardMoney(platformAwardMoney);
        orderSubmitResult.setShopAwardMoney(shopAwardMoney);
        return orderSubmitResult;
    }



    //--------------------订单回滚

    // 重量参与配送费计算
    private static OrderSubmitCalResult doOrderWeightDeliveryPrice(Integer isZiQu, Double totalWeight, Double
            deliveryPrice, ShopInfo shopInfo, Long cityAgentId,
                                                                   OrderSubmitCalResult orderSubmitResult) {
        if (null != isZiQu && 0 == isZiQu && totalWeight != null) {
            if (shopInfo != null) {
                if (deliveryPrice == null) {
                    deliveryPrice = 0.0d;
                }
                Double fixedWeightCost = shopInfo.getFixedWeightCost();
                Double withinWeight = shopInfo.getWithinWeight();
                Double oneKgWeightCost = shopInfo.getOneKgWeightCost();
                if (ValidateUtil.isNotAbsDouble(fixedWeightCost)
                        && ValidateUtil.isNotAbsDouble(withinWeight)
                        && ValidateUtil.isNotAbsDouble(oneKgWeightCost)
                ) {
                    // 商圈的
                    if (ValidateUtil.isID(cityAgentId)) {
                        CityAgent cityAgent = CityAgentMemory.getInstance().getById(cityAgentId);
                        if (cityAgent != null) {
                            fixedWeightCost = cityAgent.getFixedWeightCost();
                            withinWeight = cityAgent.getWithinWeight();
                            oneKgWeightCost = cityAgent.getOneKgWeightCost();
                        }
                    }
                }

                // 若没有 就不在计算了
                if (ValidateUtil.isNotAbsDouble(fixedWeightCost)
                        && ValidateUtil.isNotAbsDouble(withinWeight)
                        && ValidateUtil.isNotAbsDouble(oneKgWeightCost)
                ) {
                } else {
                    if (JYMathDoubleUtils.sub(totalWeight, withinWeight) <= 0) {
                        deliveryPrice = JYMathDoubleUtils.add(deliveryPrice, fixedWeightCost);
                    } else {
                        Double after = JYMathDoubleUtils.sub(totalWeight, withinWeight);
                        deliveryPrice = JYMathDoubleUtils.add(deliveryPrice, JYMathDoubleUtils.add(fixedWeightCost, JYMathDoubleUtils.mul(after, oneKgWeightCost)));
                    }
                    orderSubmitResult.setOrderDeliveryPrice(deliveryPrice);
                }
            }
        }
        return orderSubmitResult;
    }

    //配送费处理
    private static OrderSubmitCalResult doDeliveryPrice(Integer isZiQu, ShopInfo shopInfo,
                                                        UserAddress userAddress, Long agentId,
                                                        CityAgent cityAgent, Double deliveryPrice,
                                                        Double buyLat, Double buyLng,
                                                        OrderSubmitCalResult orderSubmitResult) {
        if (null != isZiQu && 0 == isZiQu) {//需要配送
            if (ValidateUtil.isNotLatLng(shopInfo.getLat(), shopInfo.getLng())) {
                orderSubmitResult.setSuccess(false);
                orderSubmitResult.setError("店铺位置信息不准确，请联系客服");
                return orderSubmitResult;
            }

            //验证配送范围
            if (null != SYS_SETTINGS.SHOP_MANAGE_TYPE && 0 == SHOP_MANAGE_TYPE_FREE_OR_AGENT.AGENT - SYS_SETTINGS.SHOP_MANAGE_TYPE) {
                //如果是按学校这种精确配送员的  需要验证店铺对应的收货地址是在同一个范围内吗
                if (null != userAddress) { //收货地址方式
                    if (ValidateUtil.isAbsLong(userAddress.getAgentId())) {//地址里有代理
                        if (0 != userAddress.getAgentId() - agentId) {
                            orderSubmitResult.setSuccess(false);
                            orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服");
                            return orderSubmitResult;
                        }
                    } else {//地址里没有代理  验证用户的收货地址，是否在店铺所在代理的配送范围
                        if (null != SYS_SETTINGS.USER_ADDRESS_IS_AGENT && 0 != 1 - SYS_SETTINGS.USER_ADDRESS_IS_AGENT) {
                            Integer postRange = cityAgent.getRang();
                            if (ValidateUtil.isNotAbsInteger(postRange)) {
                                postRange = 0;
                            }
                            if (ValidateUtil.isNotLatLng(cityAgent.getLat(), cityAgent.getLng())) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("店铺所在商圈未设置经纬度，请联系客服");
                                return orderSubmitResult;
                            }

                            //验证收货距离
                            double distinct = Geohash.distance(cityAgent.getLat(), cityAgent.getLng(), userAddress.getLat(), userAddress.getLng());
                            if (JYMathDoubleUtils.sub(distinct, JYMathDoubleUtils.mul(postRange, 1000)) > 0) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出商圈的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }

                            //验证收货地址距离店铺是否超出距离
                            if (null != shopInfo) {
                                double distinctShop = Geohash.distance(shopInfo.getLat(), shopInfo.getLng(), userAddress.getLat(), userAddress.getLng());
                                if (JYMathDoubleUtils.sub(distinctShop, JYMathDoubleUtils.mul(postRange, 1000)) > 0) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                    return orderSubmitResult;
                                }
                            }

                        }
                    }

                    //配送费计算方式
                    if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 2 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) { //配送费计算方式 1固定配送费 2 按距离（平台）计算 3按距离（店铺）
                        //2 按距离（平台）计算
                        if (ValidateUtil.isNotLatLng(userAddress.getLat(), userAddress.getLng())) {
                            orderSubmitResult.setSuccess(false);
                            orderSubmitResult.setError("收货地址信息无效，请重新添加地址");
                            return orderSubmitResult;
                        }
                        //验证按距离计算的配送费是否正确
                        Double distance = Geohash.distance(userAddress.getLat(), userAddress.getLng(), shopInfo.getLat(), shopInfo.getLng());//根据两点的经纬度计算距离
                        SysVariablePaotui sysVariablePaotui = SysVariablePaotuiMemory.getInstance().getByCode(7);
                        Double km = JYMathDoubleUtils.div(distance, 1000);

                        if (null != cityAgent) {
                            Integer postRange = cityAgent.getRang();
                            if (JYMathDoubleUtils.sub(km, postRange) > 0) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }
                        }

                        if (sysVariablePaotui != null) {
                            if (km - Double.parseDouble(sysVariablePaotui.getRang()) <= 0) {
                                String money = sysVariablePaotui.getVal();
                                if (ValidateUtil.isNotNull(money)) {
                                    deliveryPrice = Double.parseDouble(money);
                                }
                            } else {
//                                Double after = km - Double.parseDouble(sysVariablePaotui.getRang());
                                Double after = JYMathDoubleUtils.sub(km, Double.parseDouble(sysVariablePaotui.getRang()));
                                Double round = Math.ceil(after);
//                                String money = String.valueOf(Double.parseDouble(sysVariablePaotui.getVal()) + (round * Double.parseDouble(sysVariablePaotui.getPre())));
//                                if (ValidateUtil.isNotNull(money)) {
//                                    deliveryPrice = Double.parseDouble(money);
//                                }
                                deliveryPrice = JYMathDoubleUtils.add(Double.parseDouble(sysVariablePaotui.getVal()), JYMathDoubleUtils.mul(round, Double.parseDouble(sysVariablePaotui.getPre())));
                            }
                        } else {
                            orderSubmitResult.setSuccess(false);
                            orderSubmitResult.setError("查不到配置参数");
                            return orderSubmitResult;
                        }
                    } else if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 3 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) {
                        // 3按距离（店铺）
                        if (ValidateUtil.isNotLatLng(userAddress.getLat(), userAddress.getLng())) {
                            orderSubmitResult.setSuccess(false);
                            orderSubmitResult.setError("收货地址信息无效，请重新添加地址");
                            return orderSubmitResult;
                        }

                        //验证按距离(店铺)计算的配送费是否正确
                        Double distance = Geohash.distance(userAddress.getLat(), userAddress.getLng(), shopInfo.getLat(), shopInfo.getLng());//根据两点的经纬度计算距离
                        Double km = JYMathDoubleUtils.div(distance, 1000);//距离
                        if (null != cityAgent) {
                            Integer postRange = cityAgent.getRang();
                            if (JYMathDoubleUtils.sub(km, postRange) > 0) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }
                        }

                        //价格计算方式：基础配送费+上取整（实际下单距离-基础范围）*超出后每公里的价格

                        //v2 店铺没有这只规则的时候，使用平台的规则
                        //withinDistance 范围
                        Double withinDistance = shopInfo.getWithinDistance();
                        //fixedCost 范围内价格
                        Double fixedCost = shopInfo.getFixedCost();
                        //oneKmCost 超出后每公里价格
                        Double oneKmCost = shopInfo.getOneKmCost();
                        if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
                            //店铺未设置规则
                            //查看商圈的公式值
                            if (null == cityAgent) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("配送费规则设置的不正确，请联系客服");
                                return orderSubmitResult;
                            }
                            //withinDistance 范围
                            withinDistance = cityAgent.getWithinDistance();
                            //fixedCost 范围内价格
                            fixedCost = cityAgent.getFixedCost();
                            //oneKmCost 超出后每公里价格
                            oneKmCost = cityAgent.getOneKmCost();
                        }
                        if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
                            //不收配送费
                        } else {
                            if (km - withinDistance <= 0) {
                                deliveryPrice = fixedCost;
                            } else {
//                                Double after = km - withinDistance;
                                Double after = JYMathDoubleUtils.sub(km, withinDistance);
                                Double round = Math.ceil(after);
//                                deliveryPrice = fixedCost + round * oneKmCost;
                                deliveryPrice = JYMathDoubleUtils.add(fixedCost, JYMathDoubleUtils.mul(round, oneKmCost));
                            }
                        }

//                        //v1 只按店铺的规则
//                        if (shopInfo.getFixedCost() != null && shopInfo.getOneKmCost() != null && shopInfo.getWithinDistance() != null) {
//                            if (km - shopInfo.getWithinDistance() <= 0) {
//                                deliveryPrice = shopInfo.getFixedCost();
//                            } else {
//                                Double after = km - shopInfo.getWithinDistance();
//                                Double round = Math.ceil(after);
//                                deliveryPrice = shopInfo.getFixedCost() + round * shopInfo.getOneKmCost();
//                            }
//                        } else {
//                            orderSubmitResult.setSuccess(false);
//                            orderSubmitResult.setError("查不到配置参数");
//                            return orderSubmitResult;
//                        }


                    }
                } else { //传入经纬度方式
                    if (null != SYS_SETTINGS.USER_ADDRESS_IS_AGENT && 0 != 1 - SYS_SETTINGS.USER_ADDRESS_IS_AGENT) {
                        Integer postRange = cityAgent.getRang();
                        if (ValidateUtil.isNotAbsInteger(postRange)) {
                            postRange = 0;
                        }
                        if (ValidateUtil.isNotLatLng(cityAgent.getLat(), cityAgent.getLng())) {
                            orderSubmitResult.setSuccess(false);
                            orderSubmitResult.setError("店铺所在商圈未设置经纬度，请联系客服");
                            return orderSubmitResult;
                        }

                        //验证收货距离
                        double distinct = Geohash.distance(cityAgent.getLat(), cityAgent.getLng(), buyLat, buyLng);
                        if (JYMathDoubleUtils.sub(distinct, JYMathDoubleUtils.mul(postRange, 1000)) > 0) {
                            orderSubmitResult.setSuccess(false);
                            orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                            return orderSubmitResult;
                        }

                        if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 2 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) { //配送费计算方式 1固定配送费
                            // 2按距离计算(平台)
                            if (ValidateUtil.isNotLatLng(buyLat, buyLng)) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("收货地址信息无效，请重新添加地址");
                                return orderSubmitResult;
                            }

                            //验证按距离计算的配送费是否正确
                            Double distance = Geohash.distance(buyLat, buyLng, shopInfo.getLat(), shopInfo.getLng()); // 上边逻辑不通
                            SysVariablePaotui sysVariablePaotui = SysVariablePaotuiMemory.getInstance().getByCode(7);
                            Double km = JYMathDoubleUtils.div(distance, 1000);
                            //验证收货地址距离店铺是否超出距离
                            if (JYMathDoubleUtils.sub(km, postRange) > 0) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }

                            if (sysVariablePaotui != null) {
                                if (km - Double.parseDouble(sysVariablePaotui.getRang()) <= 0) {
                                    String money = sysVariablePaotui.getVal();
                                    if (ValidateUtil.isNotNull(money)) {
                                        deliveryPrice = Double.parseDouble(money);
                                    }
                                } else {
//                                    Double after = km - Double.parseDouble(sysVariablePaotui.getRang());
                                    Double after = JYMathDoubleUtils.sub(km, Double.parseDouble(sysVariablePaotui.getRang()));
                                    Double round = Math.ceil(after);
//                                    String money = String.valueOf(Double.parseDouble(sysVariablePaotui.getVal()) + (round * Double.parseDouble(sysVariablePaotui.getPre())));
//                                    if (ValidateUtil.isNotNull(money)) {
//                                        deliveryPrice = Double.parseDouble(money);
//                                    }
                                    deliveryPrice = JYMathDoubleUtils.add(Double.parseDouble(sysVariablePaotui.getVal()), JYMathDoubleUtils.mul(round, Double.parseDouble(sysVariablePaotui.getPre())));
                                }
                            } else {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("查不到配置参数");
                                return orderSubmitResult;
                            }
                        } else if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 3 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) {
                            // 3按距离（店铺）
                            if (ValidateUtil.isNotLatLng(buyLat, buyLng)) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("收货地址信息无效，请重新添加地址");
                                return orderSubmitResult;
                            }

                            //验证按距离(店铺)计算的配送费是否正确
                            Double distance = Geohash.distance(buyLat, buyLng, shopInfo.getLat(), shopInfo.getLng()); // 上边逻辑不通
                            Double km = JYMathDoubleUtils.div(distance, 1000);
                            //验证收货地址距离店铺是否超出距离
                            if (JYMathDoubleUtils.sub(km, postRange) > 0) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }


                            //v2 店铺没有这只规则的时候，使用平台的规则
                            //withinDistance 范围
                            Double withinDistance = shopInfo.getWithinDistance();
                            //fixedCost 范围内价格
                            Double fixedCost = shopInfo.getFixedCost();
                            //oneKmCost 超出后每公里价格
                            Double oneKmCost = shopInfo.getOneKmCost();
                            if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
                                //店铺未设置规则
                                //查看商圈的公式值
                                if (null == cityAgent) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("配送费规则设置的不正确，请联系客服");
                                    return orderSubmitResult;
                                }
                                //withinDistance 范围
                                withinDistance = cityAgent.getWithinDistance();
                                //fixedCost 范围内价格
                                fixedCost = cityAgent.getFixedCost();
                                //oneKmCost 超出后每公里价格
                                oneKmCost = cityAgent.getOneKmCost();
                            }
                            if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
                                //不收配送费
                            } else {
                                if (km - withinDistance <= 0) {
                                    deliveryPrice = fixedCost;
                                } else {
                                    Double after = km - withinDistance;
                                    Double round = Math.ceil(after);
//                                    deliveryPrice = fixedCost + round * oneKmCost;
                                    deliveryPrice = JYMathDoubleUtils.add(fixedCost, JYMathDoubleUtils.mul(round, oneKmCost));
                                }
                            }

//                        //v1 只按店铺的规则
//                            if (shopInfo.getFixedCost() != null && shopInfo.getOneKmCost() != null && shopInfo.getWithinDistance() != null) {
//
//                                if (km - shopInfo.getWithinDistance() <= 0) {
//                                    deliveryPrice = shopInfo.getFixedCost();
//                                } else {
//                                    Double after = km - shopInfo.getWithinDistance();
//                                    Double round = Math.ceil(after);
//                                    deliveryPrice = shopInfo.getFixedCost() + round * shopInfo.getOneKmCost();
//                                }
//                            } else {
//                                orderSubmitResult.setSuccess(false);
//                                orderSubmitResult.setError("查不到配置参数");
//                                return orderSubmitResult;
//                            }
                        }

                    }
                }
            }
        }
        orderSubmitResult.setOrderDeliveryPrice(deliveryPrice);
        return orderSubmitResult;
    }

    //配送费处理(新增围栏模式)
    private static OrderSubmitCalResult doDeliveryPriceV2(Integer isZiQu, ShopInfo shopInfo,
                                                          UserAddress userAddress, Long agentId,
                                                          CityAgent cityAgent, Double deliveryPrice,
                                                          Double buyLat, Double buyLng,
                                                          OrderSubmitCalResult orderSubmitResult) {
        if (null != isZiQu && 0 == isZiQu) {//需要配送
            if (ValidateUtil.isNotLatLng(shopInfo.getLat(), shopInfo.getLng())) {
                orderSubmitResult.setSuccess(false);
                orderSubmitResult.setError("店铺位置信息不准确，请联系客服");
                return orderSubmitResult;
            }

            //验证配送范围
            if (null != SYS_SETTINGS.SHOP_MANAGE_TYPE && 0 == SHOP_MANAGE_TYPE_FREE_OR_AGENT.AGENT - SYS_SETTINGS.SHOP_MANAGE_TYPE) {
                //如果是按学校这种精确配送员的  需要验证店铺对应的收货地址是在同一个范围内吗
                if (null != userAddress) { //收货地址方式
                    if (ValidateUtil.isAbsLong(userAddress.getAgentId())) {//地址里有代理
                        if (0 != userAddress.getAgentId() - agentId) {
                            orderSubmitResult.setSuccess(false);
                            orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服");
                            return orderSubmitResult;
                        }
                    } else {//地址里没有代理  验证用户的收货地址，是否在店铺所在代理的配送范围
                        if (null != SYS_SETTINGS.USER_ADDRESS_IS_AGENT && 0 != 1 - SYS_SETTINGS.USER_ADDRESS_IS_AGENT) {
                            Integer postRange = cityAgent.getRang();
                            if (ValidateUtil.isNotAbsInteger(postRange)) {
                                postRange = 0;
                            }

                            //验证收货距离
                            if (null != SYS_SETTINGS.IS_ELECTRONIC_FENCE && 0 == 1 - SYS_SETTINGS.IS_ELECTRONIC_FENCE) {    // 是否启用电子围栏 0.不使用电子围栏 1.使用电子围栏
                                // 判断该用户是否在商圈内(多边形)
                                if (StringUtils.isEmpty(cityAgent.getLnglats())) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("商圈经纬度无效，请联系客服");
                                    return orderSubmitResult;
                                }
                                String[] latlngs = cityAgent.getLnglats().split(";");
                                Double[] lngArr = new Double[latlngs.length];
                                Double[] latArr = new Double[latlngs.length];
                                for (int j = 0; j < latlngs.length; j++) {
                                    String[] lnla = latlngs[j].split(",");
                                    lngArr[j] = Double.parseDouble(lnla[0]);
                                    latArr[j] = Double.parseDouble(lnla[1]);
                                }
                                Boolean flag = Geohash.isInPolygon(userAddress.getLng(), userAddress.getLat(), lngArr, latArr);
                                if (!flag) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服 ");
                                    return orderSubmitResult;
                                }
                                //验证收货地址距离店铺是否超出距离
                                if (null != shopInfo) {
//                                    if (SYS_SETTINGS.DELIVERY_DISTANCE_IS_NOT_CHECK != null && SYS_SETTINGS.DELIVERY_DISTANCE_IS_NOT_CHECK == 1) {
//                                        // 地址不验证收货地址
//                                    } else {
//                                        double distinctShop = Geohash.distance(shopInfo.getLat(), shopInfo.getLng(), userAddress.getLat(), userAddress.getLng());
//                                        if (JYMathDoubleUtils.sub(distinctShop, JYMathDoubleUtils.mul(postRange, 1000)) > 0) {
//                                            orderSubmitResult.setSuccess(false);
//                                            orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
//                                            return orderSubmitResult;
//                                        }
//                                    }
                                    double distinctShop = Geohash.distance(shopInfo.getLat(), shopInfo.getLng(), userAddress.getLat(), userAddress.getLng());
                                    if (JYMathDoubleUtils.sub(distinctShop, JYMathDoubleUtils.mul(postRange, 1000)) > 0) {
                                        orderSubmitResult.setSuccess(false);
                                        orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                        return orderSubmitResult;
                                    }
                                }
                            } else if (null != SYS_SETTINGS.IS_ELECTRONIC_FENCE && 0 == 2 - SYS_SETTINGS.IS_ELECTRONIC_FENCE) {// 是否启用电子围栏 0.不使用电子围栏 1.使用商圈电子围栏 2. 使用店铺电子围栏
                                // 判断该用户是否在店铺商圈内(多边形)
                                if (StringUtils.isEmpty(shopInfo.getLnglats())) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("店铺商圈经纬度无效，请联系客服");
                                    return orderSubmitResult;
                                }
                                String[] latlngs = shopInfo.getLnglats().split(";");
                                Double[] lngArr = new Double[latlngs.length];
                                Double[] latArr = new Double[latlngs.length];
                                for (int j = 0; j < latlngs.length; j++) {
                                    String[] lnla = latlngs[j].split(",");
                                    lngArr[j] = Double.parseDouble(lnla[0]);
                                    latArr[j] = Double.parseDouble(lnla[1]);
                                }
                                Boolean flag = Geohash.isInPolygon(userAddress.getLng(), userAddress.getLat(), lngArr, latArr);
                                if (!flag) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                    return orderSubmitResult;
                                }
                            } else {
                                if (ValidateUtil.isNotLatLng(cityAgent.getLat(), cityAgent.getLng())) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("店铺所在商圈未设置经纬度，请联系客服");
                                    return orderSubmitResult;
                                }
                                double distinct = Geohash.distance(cityAgent.getLat(), cityAgent.getLng(), userAddress.getLat(), userAddress.getLng());
                                if (JYMathDoubleUtils.sub(distinct, JYMathDoubleUtils.mul(postRange, 1000)) > 0) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("您选择的收货地址超出商圈的配送范围，请重新选择地址或联系客服。");
                                    return orderSubmitResult;
                                }
                                //验证收货地址距离店铺是否超出距离
                                if (null != shopInfo) {
//                                    if (SYS_SETTINGS.DELIVERY_DISTANCE_IS_NOT_CHECK != null && SYS_SETTINGS.DELIVERY_DISTANCE_IS_NOT_CHECK == 1) {
//                                        // 地址不验证收货地址
//                                    } else {
//                                        // 然后验证判断是否验证距离
//                                        double distinctShop = Geohash.distance(shopInfo.getLat(), shopInfo.getLng(), userAddress.getLat(), userAddress.getLng());
//                                        if (JYMathDoubleUtils.sub(distinctShop, JYMathDoubleUtils.mul(postRange, 1000)) > 0) {
//                                            orderSubmitResult.setSuccess(false);
//                                            orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
//                                            return orderSubmitResult;
//                                        }
//                                    }
                                    // 然后验证判断是否验证距离
                                    double distinctShop = Geohash.distance(shopInfo.getLat(), shopInfo.getLng(), userAddress.getLat(), userAddress.getLng());
                                    if (JYMathDoubleUtils.sub(distinctShop, JYMathDoubleUtils.mul(postRange, 1000)) > 0) {
                                        orderSubmitResult.setSuccess(false);
                                        orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                        return orderSubmitResult;
                                    }
                                }
                            }
                        }
                    }

                    //配送费计算方式
                    if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 2 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) { //配送费计算方式 1固定配送费 2 按距离（平台）计算 3按距离（店铺）
                        //2 按距离（平台）计算
                        if (ValidateUtil.isNotLatLng(userAddress.getLat(), userAddress.getLng())) {
                            orderSubmitResult.setSuccess(false);
                            orderSubmitResult.setError("收货地址信息无效，请重新添加地址");
                            return orderSubmitResult;
                        }
                        //验证按距离计算的配送费是否正确
                        Double distance = Geohash.distance(userAddress.getLat(), userAddress.getLng(), shopInfo.getLat(), shopInfo.getLng());//根据两点的经纬度计算距离(店铺，收货地址)
                        SysVariablePaotui sysVariablePaotui = SysVariablePaotuiMemory.getInstance().getByCode(7);
                        Double km = JYMathDoubleUtils.div(distance, 1000);

                        if (null != cityAgent) {
                            Integer postRange = cityAgent.getRang();
                            if (JYMathDoubleUtils.sub(km, postRange) > 0) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }
                        }

                        if (sysVariablePaotui != null) {
                            if (km - Double.parseDouble(sysVariablePaotui.getRang()) <= 0) {
                                String money = sysVariablePaotui.getVal();
                                if (ValidateUtil.isNotNull(money)) {
                                    deliveryPrice = Double.parseDouble(money);
                                }
                            } else {
//                                Double after = km - Double.parseDouble(sysVariablePaotui.getRang());
                                Double after = JYMathDoubleUtils.sub(km, Double.parseDouble(sysVariablePaotui.getRang()));
                                Double round = Math.ceil(after);
//                                String money = String.valueOf(Double.parseDouble(sysVariablePaotui.getVal()) + (round * Double.parseDouble(sysVariablePaotui.getPre())));
//                                if (ValidateUtil.isNotNull(money)) {
//                                    deliveryPrice = Double.parseDouble(money);
//                                }
                                deliveryPrice = JYMathDoubleUtils.add(Double.parseDouble(sysVariablePaotui.getVal()), JYMathDoubleUtils.mul(round, Double.parseDouble(sysVariablePaotui.getPre())));
                            }
                        } else {
                            orderSubmitResult.setSuccess(false);
                            orderSubmitResult.setError("查不到配置参数");
                            return orderSubmitResult;
                        }
                    } else if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 3 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) {
                        // 3按距离（店铺）
                        if (ValidateUtil.isNotLatLng(userAddress.getLat(), userAddress.getLng())) {
                            orderSubmitResult.setSuccess(false);
                            orderSubmitResult.setError("收货地址信息无效，请重新添加地址");
                            return orderSubmitResult;
                        }
                        //验证按距离(店铺)计算的配送费是否正确
                        Double distance = Geohash.distance(userAddress.getLat(), userAddress.getLng(), shopInfo.getLat(), shopInfo.getLng());//根据两点的经纬度计算距离
                        Double km = JYMathDoubleUtils.div(distance, 1000);//距离
                        if (null != cityAgent) {
                            Integer postRange = cityAgent.getRang();
                            if (JYMathDoubleUtils.sub(km, postRange) > 0) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }
                        }

                        //价格计算方式：基础配送费+上取整（实际下单距离-基础范围）*超出后每公里的价格

                        //v2 店铺没有这只规则的时候，使用平台的规则
                        //withinDistance 范围
                        Double withinDistance = shopInfo.getWithinDistance();
                        //fixedCost 范围内价格
                        Double fixedCost = shopInfo.getFixedCost();
                        //oneKmCost 超出后每公里价格
                        Double oneKmCost = shopInfo.getOneKmCost();
                        if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
                            //店铺未设置规则
                            //查看商圈的公式值
                            if (null == cityAgent) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("配送费规则设置的不正确，请联系客服");
                                return orderSubmitResult;
                            }
                            //withinDistance 范围
                            withinDistance = cityAgent.getWithinDistance();
                            //fixedCost 范围内价格
                            fixedCost = cityAgent.getFixedCost();
                            //oneKmCost 超出后每公里价格
                            oneKmCost = cityAgent.getOneKmCost();
                        }
                        if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
                            //不收配送费
                        } else {
                            if (km - withinDistance <= 0) {
                                deliveryPrice = fixedCost;
                            } else {
//                                Double after = km - withinDistance;
                                Double after = JYMathDoubleUtils.sub(km, withinDistance);
                                Double round = Math.ceil(after);
//                                deliveryPrice = fixedCost + round * oneKmCost;
                                deliveryPrice = JYMathDoubleUtils.add(fixedCost, JYMathDoubleUtils.mul(round, oneKmCost));
                            }
                        }

//                        //v1 只按店铺的规则
//                        if (shopInfo.getFixedCost() != null && shopInfo.getOneKmCost() != null && shopInfo.getWithinDistance() != null) {
//                            if (km - shopInfo.getWithinDistance() <= 0) {
//                                deliveryPrice = shopInfo.getFixedCost();
//                            } else {
//                                Double after = km - shopInfo.getWithinDistance();
//                                Double round = Math.ceil(after);
//                                deliveryPrice = shopInfo.getFixedCost() + round * shopInfo.getOneKmCost();
//                            }
//                        } else {
//                            orderSubmitResult.setSuccess(false);
//                            orderSubmitResult.setError("查不到配置参数");
//                            return orderSubmitResult;
//                        }


                    }
                } else { //传入经纬度方式
                    if (null != SYS_SETTINGS.USER_ADDRESS_IS_AGENT && 0 != 1 - SYS_SETTINGS.USER_ADDRESS_IS_AGENT) {
                        Integer postRange = cityAgent.getRang();
                        if (ValidateUtil.isNotAbsInteger(postRange)) {
                            postRange = 0;
                        }

                        // 是否启用电子围栏 0.不使用电子围栏 1.使用电子围栏
                        if (null != SYS_SETTINGS.IS_ELECTRONIC_FENCE && 0 == 1 - SYS_SETTINGS.IS_ELECTRONIC_FENCE) {
                            // 判断该用户是否在商圈内(多边形)
                            if (StringUtils.isEmpty(cityAgent.getLnglats())) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("商圈经纬度无效，请联系客服");
                                return orderSubmitResult;
                            }
                            String[] latlngs = cityAgent.getLnglats().split(";");
                            Double[] lngArr = new Double[latlngs.length];
                            Double[] latArr = new Double[latlngs.length];
                            for (int j = 0; j < latlngs.length; j++) {
                                String[] lnla = latlngs[j].split(",");
                                lngArr[j] = Double.parseDouble(lnla[0]);
                                latArr[j] = Double.parseDouble(lnla[1]);
                            }
                            if (ValidateUtil.isNotLatLng(userAddress.getLat(), userAddress.getLng())) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出该商圈的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }
                            Boolean flag = Geohash.isInPolygon(userAddress.getLng(), userAddress.getLat(), lngArr, latArr);
                            if (!flag) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出该商圈的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }
                        } else if (null != SYS_SETTINGS.IS_ELECTRONIC_FENCE && 0 == 2 - SYS_SETTINGS.IS_ELECTRONIC_FENCE) {// 是否启用电子围栏 0.不使用电子围栏 1.使用商圈电子围栏 2. 使用店铺电子围栏
                            // 判断该用户是否在店铺商圈内(多边形)
                            if (StringUtils.isEmpty(shopInfo.getLnglats())) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("店铺商圈经纬度无效，请联系客服");
                                return orderSubmitResult;
                            }
                            String[] latlngs = shopInfo.getLnglats().split(";");
                            Double[] lngArr = new Double[latlngs.length];
                            Double[] latArr = new Double[latlngs.length];
                            for (int j = 0; j < latlngs.length; j++) {
                                String[] lnla = latlngs[j].split(",");
                                lngArr[j] = Double.parseDouble(lnla[0]);
                                latArr[j] = Double.parseDouble(lnla[1]);
                            }
                            Boolean flag = Geohash.isInPolygon(userAddress.getLng(), userAddress.getLat(), lngArr, latArr);
                            if (!flag) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }
                        } else {
                            if (ValidateUtil.isNotLatLng(cityAgent.getLat(), cityAgent.getLng())) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("店铺所在商圈未设置经纬度，请联系客服");
                                return orderSubmitResult;
                            }
                            //验证收货距离
                            double distinct = Geohash.distance(cityAgent.getLat(), cityAgent.getLng(), buyLat, buyLng);
                            if (JYMathDoubleUtils.sub(distinct, JYMathDoubleUtils.mul(postRange, 1000)) > 0) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }
                        }


                        if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 2 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) { //配送费计算方式 1固定配送费
                            // 2按距离计算(平台)
                            if (ValidateUtil.isNotLatLng(buyLat, buyLng)) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("收货地址信息无效，请重新添加地址");
                                return orderSubmitResult;
                            }

                            //验证按距离计算的配送费是否正确
                            Double distance = Geohash.distance(buyLat, buyLng, shopInfo.getLat(), shopInfo.getLng()); // 上边逻辑不通
                            SysVariablePaotui sysVariablePaotui = SysVariablePaotuiMemory.getInstance().getByCode(7);
                            Double km = JYMathDoubleUtils.div(distance, 1000);
                            //验证收货地址距离店铺是否超出距离
                            if (JYMathDoubleUtils.sub(km, postRange) > 0) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }

                            if (sysVariablePaotui != null) {
                                if (km - Double.parseDouble(sysVariablePaotui.getRang()) <= 0) {
                                    String money = sysVariablePaotui.getVal();
                                    if (ValidateUtil.isNotNull(money)) {
                                        deliveryPrice = Double.parseDouble(money);
                                    }
                                } else {
//                                    Double after = km - Double.parseDouble(sysVariablePaotui.getRang());
                                    Double after = JYMathDoubleUtils.sub(km, Double.parseDouble(sysVariablePaotui.getRang()));
                                    Double round = Math.ceil(after);
//                                    String money = String.valueOf(Double.parseDouble(sysVariablePaotui.getVal()) + (round * Double.parseDouble(sysVariablePaotui.getPre())));
//                                    if (ValidateUtil.isNotNull(money)) {
//                                        deliveryPrice = Double.parseDouble(money);
//                                    }
                                    deliveryPrice = JYMathDoubleUtils.add(Double.parseDouble(sysVariablePaotui.getVal()), JYMathDoubleUtils.mul(round, Double.parseDouble(sysVariablePaotui.getPre())));
                                }
                            } else {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("查不到配置参数");
                                return orderSubmitResult;
                            }
                        } else if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 3 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) {
                            // 3按距离（店铺）
                            if (ValidateUtil.isNotLatLng(buyLat, buyLng)) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("收货地址信息无效，请重新添加地址");
                                return orderSubmitResult;
                            }

                            //验证按距离(店铺)计算的配送费是否正确
                            Double distance = Geohash.distance(buyLat, buyLng, shopInfo.getLat(), shopInfo.getLng()); // 上边逻辑不通
                            Double km = JYMathDoubleUtils.div(distance, 1000);
                            //验证收货地址距离店铺是否超出距离
                            if (JYMathDoubleUtils.sub(km, postRange) > 0) {
                                orderSubmitResult.setSuccess(false);
                                orderSubmitResult.setError("您选择的收货地址超出该店铺的配送范围，请重新选择地址或联系客服。");
                                return orderSubmitResult;
                            }


                            //v2 店铺没有这只规则的时候，使用平台的规则
                            //withinDistance 范围
                            Double withinDistance = shopInfo.getWithinDistance();
                            //fixedCost 范围内价格
                            Double fixedCost = shopInfo.getFixedCost();
                            //oneKmCost 超出后每公里价格
                            Double oneKmCost = shopInfo.getOneKmCost();
                            if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
                                //店铺未设置规则
                                //查看商圈的公式值
                                if (null == cityAgent) {
                                    orderSubmitResult.setSuccess(false);
                                    orderSubmitResult.setError("配送费规则设置的不正确，请联系客服");
                                    return orderSubmitResult;
                                }
                                //withinDistance 范围
                                withinDistance = cityAgent.getWithinDistance();
                                //fixedCost 范围内价格
                                fixedCost = cityAgent.getFixedCost();
                                //oneKmCost 超出后每公里价格
                                oneKmCost = cityAgent.getOneKmCost();
                            }
                            if (ValidateUtil.isNotAbsDouble(withinDistance) && ValidateUtil.isNotAbsDouble(fixedCost) && ValidateUtil.isNotAbsDouble(oneKmCost)) {
                                //不收配送费
                            } else {
                                if (km - withinDistance <= 0) {
                                    deliveryPrice = fixedCost;
                                } else {
                                    Double after = km - withinDistance;
                                    Double round = Math.ceil(after);
//                                    deliveryPrice = fixedCost + round * oneKmCost;
                                    deliveryPrice = JYMathDoubleUtils.add(fixedCost, JYMathDoubleUtils.mul(round, oneKmCost));
                                }
                            }

//                        //v1 只按店铺的规则
//                            if (shopInfo.getFixedCost() != null && shopInfo.getOneKmCost() != null && shopInfo.getWithinDistance() != null) {
//
//                                if (km - shopInfo.getWithinDistance() <= 0) {
//                                    deliveryPrice = shopInfo.getFixedCost();
//                                } else {
//                                    Double after = km - shopInfo.getWithinDistance();
//                                    Double round = Math.ceil(after);
//                                    deliveryPrice = shopInfo.getFixedCost() + round * shopInfo.getOneKmCost();
//                                }
//                            } else {
//                                orderSubmitResult.setSuccess(false);
//                                orderSubmitResult.setError("查不到配置参数");
//                                return orderSubmitResult;
//                            }
                        }

                    }
                }
            }
        }
        orderSubmitResult.setOrderDeliveryPrice(deliveryPrice);
        return orderSubmitResult;
    }


    //活动处理
    private static OrderInfo doOrderGame(String submitUsername,
                                         List<OrderGameRulesDB> orderGameDBList,
                                         OrderInfo orderInfo,
                                         Double totalMoney) {

        Double mustPayMoney = totalMoney;//必须支付金额
        Double awardMoney = 0d;//奖励金额
        Double platformAwardMoney = 0d;//平台奖励金额
        Double shopAwardMoney = 0d;//店铺奖励金额

        Long time = DateUtils.getCurrTime();
        //活动--满减满赠
        if (ValidateUtil.isAbsList(orderGameDBList)) {
            for (int i = 0; i < orderGameDBList.size(); i++) {
                if (null == orderGameDBList.get(i)) {
                    continue;
                }
                if (ValidateUtil.isID(orderGameDBList.get(i).getGameId()) && ValidateUtil.isID(orderGameDBList.get(i).getGameRuleId())) {
                } else {
                    continue;
                }

                OrderSubmitResult saveGameInfo = saveGameInfo(orderGameDBList.get(i).getGameId(), orderGameDBList.get(i).getGameRuleId(),//多个活动同时提交
                        orderInfo, time,
                        totalMoney,
                        awardMoney, platformAwardMoney, shopAwardMoney,
                        mustPayMoney,
                        submitUsername);
                if (null == saveGameInfo) {
                    return null;
                }

                if (!saveGameInfo.isSuccess()) {
                    return null;
                }
                platformAwardMoney = saveGameInfo.getPlatformAwardMoney();
                shopAwardMoney = saveGameInfo.getShopAwardMoney();
                orderInfo.setAwardMoney(saveGameInfo.getAwardMoney());
                orderInfo.setShopAwardMoney(shopAwardMoney);
                orderInfo.setPlatformAwardMoney(platformAwardMoney);
                orderInfo.setTotalPrice(saveGameInfo.getMustPayMoney());//待支付金额
                orderInfo.setTotalMoney(saveGameInfo.getOrderTotalMoney());//订单总金额


                break;
            }
        } else {
            orderInfo.setAwardMoney(awardMoney);
            orderInfo.setPlatformAwardMoney(platformAwardMoney);
            orderInfo.setShopAwardMoney(shopAwardMoney);
            orderInfo.setTotalPrice(mustPayMoney);//待支付金额
            orderInfo.setTotalMoney(totalMoney);//订单总金额
        }

        return orderInfo;
    }


}

